package com.zego.zegowawaji_server.callback;

import android.text.TextUtils;

import com.zego.base.bean.CustomZegoUser;
import com.zego.base.http.RequestMgr;
import com.zego.base.utils.AppLogger;
import com.zego.zegoliveroom.callback.im.IZegoIMCallback;
import com.zego.zegoliveroom.constants.ZegoIM;
import com.zego.zegoliveroom.entity.ZegoBigRoomMessage;
import com.zego.zegoliveroom.entity.ZegoConversationMessage;
import com.zego.zegoliveroom.entity.ZegoRoomMessage;
import com.zego.zegoliveroom.entity.ZegoUserState;
import com.zego.zegowawaji_server.listener.IRoomClient;
import com.zego.zegowawaji_server.listener.IStateChangedListener;

import java.util.List;

/**
 * 通信回调
 */
public class ZegoIMCallack implements IZegoIMCallback {

    private IRoomClient mRoomClient;
    private IStateChangedListener mListener;

    public ZegoIMCallack(IRoomClient client, IStateChangedListener listener) {
        mRoomClient = client;
        mListener = listener;
    }

    /**
     * 房间成员更新回调
     */
    @Override
    public void onUserUpdate(ZegoUserState[] zegoUserStates, int updateType) {
        AppLogger.getInstance().writeLog("onUserUpdate, 更新类型: %d; 用户数量: %d", updateType, zegoUserStates.length);
        if (updateType == ZegoIM.UserUpdateType.Total) {
            initMembers(zegoUserStates);
        } else if (updateType == ZegoIM.UserUpdateType.Increase) {
            for (ZegoUserState state : zegoUserStates) {
                if (state.updateFlag == ZegoIM.UserUpdateFlag.Added) {
                    addMember(state);
                } else if (state.updateFlag == ZegoIM.UserUpdateFlag.Deleted) {
                    removeMember(state);
                }
            }
        }

        mListener.onRoomStateUpdate();
    }

    /**
     * 收到房间的广播消息
     */
    @Override
    public void onRecvRoomMessage(String roomId, ZegoRoomMessage[] zegoRoomMessages) {
    }

    /**
     * 收到会话消息
     */
    @Override
    public void onRecvConversationMessage(String s, String s1, ZegoConversationMessage zegoConversationMessage) {
    }

    @Override
    public void onUpdateOnlineCount(String s, int i) {
    }

    @Override
    public void onRecvBigRoomMessage(String s, ZegoBigRoomMessage[] zegoBigRoomMessages) {

    }

    private void initMembers(final ZegoUserState[] zegoUserStates) {
        mRoomClient.runOnWorkThread(new Runnable() {
            @Override
            public void run() {
                List<CustomZegoUser> allMembers = mRoomClient.getTotalUser();
                allMembers.clear();

                for (ZegoUserState state : zegoUserStates) {
                    CustomZegoUser user = new CustomZegoUser();
                    user.userID = state.userID;
                    user.userName = state.userName;
                    allMembers.add(user);
                }

                List<CustomZegoUser> queueMembers = mRoomClient.getQueueUser();
                int index = 0;
                while (true) {
                    if (index >= queueMembers.size()) break;

                    boolean isMember = false;
                    CustomZegoUser user = queueMembers.get(index);
                    for (CustomZegoUser member : allMembers) {
                        if (TextUtils.equals(member.userID, user.userID)) {
                            isMember = true;
                            break;
                        }
                    }

                    if (isMember) {
                        index++;
                    } else {
                        queueMembers.remove(index);
                        if (queueMembers != null && queueMembers.size() <= 0)
                            RequestMgr.reqRoomStatus(1);
                        AppLogger.getInstance().writeLog("从队列中移除用户 %s ,因为他已经离开房间", user.userName);
                    }
                }
            }
        });
    }

    /**
     * 成员加入
     */
    private void addMember(final ZegoUserState state) {
        mRoomClient.runOnWorkThread(new Runnable() {
            @Override
            public void run() {
                List<CustomZegoUser> allMembers = mRoomClient.getTotalUser();

                boolean found = false;
                for (CustomZegoUser user : allMembers) {
                    if (TextUtils.equals(user.userID, state.userID)) {
                        found = true;
                        break;
                    }
                }

                if (!found) {
                    AppLogger.getInstance().writeLog("添加新成员, userName: %s", state.userName);
                    final CustomZegoUser newUser = new CustomZegoUser();
                    newUser.userID = state.userID;
                    newUser.userName = state.userName;

                    allMembers.add(newUser);
                } else {
                    AppLogger.getInstance().writeLog("该成员已经存在, userName: %s", state.userName);
                }
            }
        });
    }

    private void removeMember(final ZegoUserState state) {
        mRoomClient.runOnWorkThread(new Runnable() {
            @Override
            public void run() {
                List<CustomZegoUser> allMembers = mRoomClient.getTotalUser();

                CustomZegoUser member = null;
                for (CustomZegoUser user : allMembers) {
                    if (TextUtils.equals(user.userID, state.userID)) {
                        member = user;
                        break;
                    }
                }

                if (member != null) {
                    AppLogger.getInstance().writeLog("在所有用户中移除用户, userName: %s", state.userName);
                    allMembers.remove(member);
                } else {
                    AppLogger.getInstance().writeLog("为找到需要移除的用户: %s", state.userName);
                }

                List<CustomZegoUser> queueMembers = mRoomClient.getQueueUser();
                member = null;
                for (CustomZegoUser user : queueMembers) {
                    if (TextUtils.equals(user.userID, state.userID)) {
                        member = user;
                        break;
                    }
                }

                if (member != null) {
                    AppLogger.getInstance().writeLog("在队列中移除用户, userName: %s", state.userName);
                    queueMembers.remove(member);
                } else {
                    AppLogger.getInstance().writeLog("在队列中未找到需要移除的用户: %s", state.userName);
                }
            }
        });
    }
}
